#coding:utf-8
from django.shortcuts import render,render_to_response
from django.http import FileResponse,HttpResponse
from django.shortcuts import render, redirect
import traceback
# Create your views here.
from django.http import StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import FileSystemStorage
from django.core.files.base import ContentFile
import os
from . import models
from .forms import UserForm,RegisterForm
import hashlib



def hash_code(s, salt='mysite'):  # 加点盐
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())  # update方法只接收bytes类型
    return h.hexdigest()

import cv2
import time

fs = FileSystemStorage(location='videos')

from django.shortcuts import render, redirect


@csrf_exempt
def index(request):
    pass
    return render(request, 'login/index.html')

@csrf_exempt
def login(request):
    if request.session.get('is_login', None):
        return redirect("/index/")
    if request.method == "POST":
        login_form = UserForm(request.POST)
        message = "请检查填写的内容！"
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            try:
                user = models.User.objects.get(name=username)
                if user.password == hash_code(password):  # 哈希值和数据库内的值进行比对
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    return redirect('/index/')
                else:
                    message = "密码不正确！"
            except:
                message = "用户不存在！"
        return render(request, 'login/login.html', locals())

    login_form = UserForm()
    return render(request, 'login/login.html', locals())

@csrf_exempt
def register(request):
    if request.session.get('is_login', None):
        # 登录状态不允许注册。你可以修改这条原则！
        return redirect("/index/")
    if request.method == "POST":
        register_form = RegisterForm(request.POST)
        message = "请检查填写的内容！"
        if register_form.is_valid():  # 获取数据
            username = register_form.cleaned_data['username']
            password1 = register_form.cleaned_data['password1']
            password2 = register_form.cleaned_data['password2']
            email = register_form.cleaned_data['email']
            sex = register_form.cleaned_data['sex']
            if password1 != password2:  # 判断两次密码是否相同
                message = "两次输入的密码不同！"
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = models.User.objects.filter(name=username)
                if same_name_user:  # 用户名唯一
                    message = '用户已经存在，请重新选择用户名！'
                    return render(request, 'login/register.html', locals())
                same_email_user = models.User.objects.filter(email=email)
                if same_email_user:  # 邮箱地址唯一
                    message = '该邮箱地址已被注册，请使用别的邮箱！'
                    return render(request, 'login/register.html', locals())

                # 当一切都OK的情况下，创建新用户

                new_user = models.User.objects.create()
                new_user.name = username
                new_user.password = hash_code(password1)  # 使用加密密码
                new_user.email = email
                new_user.sex = sex
                new_user.save()
                return redirect('/login/')  # 自动跳转到登录页面
    register_form = RegisterForm()
    return render(request, 'login/register.html', locals())


def logout(request):
    if not request.session.get('is_login', None):
        return redirect('/index/')
    request.session.flush()
    return redirect('/index/')

@csrf_exempt
def fileupload(request):
    if request.session.get('is_login', None):
        # return redirect("/index/")
        if request.method == 'POST':
            upload_file = request.FILES.get('file')
            task = request.POST.get('task_id')  # 获取文件唯一标识符
            chunk = request.POST.get('chunk', 0)  # 获取该分片在所有分片中的序号
            filename = '%s%s' % (task, chunk)  # 构成该分片唯一标识符
            print("filename=",filename)
            fs.save('./upload/%s' % filename,ContentFile(upload_file.read()))  # 保存分片到本地
        return render_to_response('upload.html',locals())
    else:
        return redirect("/index/")

@csrf_exempt
def fileMerge(request):
    try:
        if request.session.get('is_login', None):
            # return redirect("/index/")
            print(request.GET)
            task = request.GET.get('task_id')
            ext = request.GET.get('filename', '')
            upload_type = request.GET.get('type')
            if len(ext) == 0 and upload_type:
                ext = upload_type.split('/')[1]
            ext = '' if len(ext) == 0 else '.%s' % ext  # 构建文件后缀名
            chunk = 0
            with open('videos/upload/%s%s' % (task, ext), 'wb') as target_file:  # 创建新文件
                while True:
                    try:
                        filename = 'videos/upload/%s%d' % (task, chunk)
                        source_file = open(filename, 'rb')  # 按序打开每个分片
                        target_file.write(source_file.read())  # 读取分片内容写入新文件
                        source_file.close()
                    except IOError:
                        break
                    chunk += 1
                    os.remove(filename)  # 删除该分片，节约空间
            the_file_name = do_deal_with_video(target_file)
            # if os.path.exists(target_file):
            #     os.remove(target_file)
            return HttpResponse(the_file_name)
        else:
            return redirect("/index/")

    except Exception as e:
        traceback.print_exc()
        return HttpResponse(traceback.format_exc())

@csrf_exempt
def file_list(request):
    if request.session.get('is_login', None):
        file_list = []
        for file in os.listdir("result"):
            file_list.append(file)
        return render(request, 'file_list.html', {'file_list': file_list})
    else:
        return redirect("/index/")

@csrf_exempt
def delete_filename(request):
    if request.session.get('is_login', None):
        if request.method == 'GET':
            if "file_name" in request.GET:
                the_file_name = request.GET['file_name']
                the_file_name = 'result/'+the_file_name
                if os.path.exists(the_file_name):
                    os.remove(the_file_name)
                    return redirect('../file_list')
                else:
                    return redirect('../file_list')
            else:
                return redirect('../file_list')
        else:
            return redirect('../file_list')
    else:
        return redirect("/index/")

@csrf_exempt
def down_load(request):
    if request.session.get('is_login', None):
        if request.method == 'GET':
            if "file_name" in request.GET:
                the_file_name = request.GET['file_name']
                the_file_name = the_file_name.split('/')[-1]
                file = open("result/"+the_file_name, 'rb')  # 设置HttpResponse的类型
                response = FileResponse(file)
                response['Content-Type'] = 'application/octet-stream'
                response['Content-Disposition'] = 'attachment;filename="result.txt"'
                # 用户可以下载books.csv文件
                return response
        else:
            return HttpResponse("")
    else:
        return redirect("/index/")


def do_deal_with_video(vfile):
    # 2. process video
    nframe = 0
    cap = cv2.VideoCapture(vfile.name)
    file_name='result/'
    for s in vfile.name.split('.')[1:]:
        file_name +=s
    while True:
        ret, frame = cap.read()
        nframe += 1
        if ret == 0:
            break

    file_name = file_name+'.txt'
    f = open(file_name, 'w+')
    print('%d' % nframe)
    f.write('%d' % nframe)
    f.close()
    return file_name